'''
#Coding: utf-8
#Project: online-exam
#Author: rtf
#Time: 2022-07-24 15:40:14
#FileName: login.py
#Softwar: PyCharm
'''


from trump.query import get_items, get_item
from trump.utils import ok, fail
from trump.decorators import anonymous
from trump.utils import get_context, set_context
from utils.params_validate_decorator import validate_params


@anonymous
@validate_params([["username", str, True], ["password", str, True]])
async def post(app, request):
    params = request.json
    set_context(request, "need_update_session", True)

    user = await get_item(app.ctx.pool, "users_view", params.get("username"), column="username")
    role = user.get("role") if user else None
    if role == "STUDENT":
        table_name = "student"
        column_name = "student_no"
    elif role == "TEACHER":
        table_name = "teacher"
        column_name = "teacher_no"
    else:
        table_name = "manager"
        column_name = "account"

    user = await get_item(app.ctx.pool, table_name, params.get("username"), column=column_name)

    if not user:
        return fail(return_msg="您的用户名错误或被禁用！")
    else:
        try:
            input_password = params.get("password")
            save_password = app.ctx.fernet.decrypt(user.get("password"))

            if input_password != save_password:
                return fail(return_msg="您的用户名或密码错误！")
        except:
            return fail(return_msg="您的账户异常, 请联系系统管理员!")
    user["role"] = role
    token = request.ctx.session.sid
    request.ctx.session["uid"] = user[column_name]
    del user["password"]

    return ok({"token": token, "profile": user})